package com.cwnu.sw.cys.core.websocket.service;

import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.AllArgsConstructor;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;

/**
 * @author jisam
 * @version 1.0
 * @contact "jisamchan@outlook.com"
 * @date 03/03/2025
 * @description 自定义握手类 废弃的
 */
@AllArgsConstructor
public class MyHandShakeHandler extends ChannelInboundHandlerAdapter {

    /**
     * WebSocket握手处理器，负责处理客户端的HTTP请求并完成WebSocket握手。
     * 继承自ChannelInboundHandlerAdapter以处理入站事件。
     */

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        /**
         * 处理接收到的通道读取事件，主要处理WebSocket握手逻辑。
         *
         * @param ctx 通道处理上下文，用于访问通道和事件派发
         * @param msg 接收到的消息对象，预期为HTTP请求或相关对象
         */
        HttpObject httpObject = (HttpObject) msg;

        // 处理WebSocket握手逻辑
        if (httpObject instanceof HttpRequest) {
            final HttpRequest req = (HttpRequest) httpObject;

            // 从请求头中提取WebSocket协议标识token
            String token = req.headers().get("Sec-Websocket-Protocol");

            // 将token保存到通道属性中以便后续使用
            Attribute<Object> token1 = ctx.channel().attr(AttributeKey.valueOf("token"));
            token1.set(token);

            // 根据请求URI和协议创建WebSocket握手工厂
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.getUri(), token, false);
            final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);

            // 如果握手协商器为空（版本不匹配），发送不支持响应
            if (handshaker == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            } else {
                // 移除当前处理器，避免重复处理
                ctx.pipeline().remove(this);

                // 执行握手并监听结果
                ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
                handshakeFuture.addListener(new ChannelFutureListener() {
                    public void operationComplete(ChannelFuture future) {
                        // 监听握手完成事件，根据结果触发相应事件
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        } else {
                            ctx.fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                        }
                    }
                });
            }
        } else {
            // 转发非HTTP请求的消息到下一个处理器
            ctx.fireChannelRead(msg);
        }
    }
}
